package com.eight.cloud.job.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.eight.cloud.job.quartz.ConcurrentJobActuator;
import com.eight.cloud.job.quartz.DisallowCConcurrentJobActuator;
import com.eight.cloud.core.global.constant.StrConstant;
import com.eight.cloud.core.global.exception.CustomException;
import com.eight.cloud.job.common.constants.ScheduleConstants;
import com.eight.cloud.job.model.vo.JobDataMapVo;
import org.quartz.*;

import static com.eight.cloud.job.common.constants.ScheduleConstants.*;


/**
 * 定时任务工具类
 *
 * @author eight
 */
public class ScheduleUtils {
    /**
     * 得到quartz任务类
     *
     * @param jobDataMap 执行计划
     * @return 具体执行任务类
     */
    private static Class<? extends Job> getQuartzJobClass(JobDataMapVo jobDataMap) {
        boolean isConcurrent = "0".equals(jobDataMap.getConcurrent());
        return isConcurrent ? ConcurrentJobActuator.class : DisallowCConcurrentJobActuator.class;
    }

    /**
     * 构建任务触发对象
     */
    public static TriggerKey getTriggerKey(String jobId, String jobGroup) {
        return TriggerKey.triggerKey(TASK_CLASS_NAME + jobId, jobGroup);
    }

    /**
     * 构建任务键对象
     */
    public static JobKey getJobKey(JobDataMapVo jobDataMap) {
        return JobKey.jobKey(jobDataMap.getTenantId() + StrConstant.DASH + jobDataMap.getJobId(),
                jobDataMap.getJobGroup());
    }

    /**
     * 创建定时任务
     */
    public static void createScheduleJob(Scheduler scheduler, JobDataMapVo jobDataMap) throws SchedulerException {
        Class<? extends Job> jobClass = getQuartzJobClass(jobDataMap);
        // 构建job信息
        String jobId = jobDataMap.getJobId();
        String jobGroup = jobDataMap.getJobGroup();
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(getJobKey(jobDataMap)).build();
        // 表达式调度构建器
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(jobDataMap.getCronExpression());
        cronScheduleBuilder = handleCronScheduleMisfirePolicy(jobDataMap, cronScheduleBuilder);
        // 按新的cronExpression表达式构建一个新的trigger
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(jobId, jobGroup))
                .withSchedule(cronScheduleBuilder).build();
        // 放入参数，运行时的方法可以获取
        jobDetail.getJobDataMap().put(TASK_PROPERTIES, jobDataMap);
        // 判断是否存在
        if (scheduler.checkExists(getJobKey(jobDataMap))) {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(getJobKey(jobDataMap));
        }
        scheduler.scheduleJob(jobDetail, trigger);
        boolean isPause = !(jobDataMap.getStatus().equals(ScheduleConstants.ExecutionJobStatus.NORMAL.getValue()) &&
                jobDataMap.getQuartzJobStatus().equals(ScheduleConstants.QuartzJobStatus.ENABLE.getValue()));
        // 暂停任务
        if (isPause) {
            scheduler.pauseJob(ScheduleUtils.getJobKey(jobDataMap));
        }
    }

    /**
     * 设置定时任务策略
     */
    public static CronScheduleBuilder handleCronScheduleMisfirePolicy(JobDataMapVo jobDataMap, CronScheduleBuilder cb) {
        switch (jobDataMap.getMisfirePolicy()) {
            case 0:
                return cb;
            case 1:
                return cb.withMisfireHandlingInstructionIgnoreMisfires();
            case 2:
                return cb.withMisfireHandlingInstructionFireAndProceed();
            case 3:
                return cb.withMisfireHandlingInstructionDoNothing();
            default:
                throw new CustomException(500, "The task misfire policy '" + jobDataMap.getMisfirePolicy()
                        + "' cannot be used in cron schedule tasks");
        }
    }

    /**
     * 检查包名是否为白名单配置
     *
     * @param invokeTarget 目标字符串
     * @return 结果
     */
    public static boolean whiteList(String invokeTarget) {
        String packageName = StrUtil.subBefore(invokeTarget, "(", false);
        int count = StrUtil.count(packageName, ".");
        if (count > 1) {
            return StrUtil.containsAnyIgnoreCase(invokeTarget, JOB_WHITELIST_STR);
        }
        Object obj = SpringUtil.getBean(StrUtil.split(invokeTarget, ".").get(0));
        return StrUtil.containsAnyIgnoreCase(obj.getClass().getPackage().getName(),
                JOB_WHITELIST_STR);
    }
}
